//
//  InboxManager.m
//  gdemm
//
//  Created by 乔明超 on 16/4/29.
//  Copyright © 2016年 Goldencis. All rights reserved.
//

#import "InboxManager.h"
#import "FileUtil.h"
#import "UserDefaultsUtil.h"
#import "ApiSupport.h"
#import "HttpUtil.h"
#import "StringUtil.h"
#import "NetManager.h"
@interface InboxManager()

@property (copy,nonatomic)  NSMutableArray *mCloudFiles;
@property (assign,nonatomic) BOOL mUnreadCountFetched;
@property (assign,nonatomic) BOOL mFetching;
@end
@implementation InboxManager
static InboxManager *mInstance;
+ (instancetype)getInstance{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        mInstance = [[InboxManager alloc]init];
    });
    return mInstance;
    
}
- (NSMutableArray *)mfiles{
    if (_mfiles == nil) {
        _mfiles = [NSMutableArray array];
    }
    return _mfiles;
}

- (NSMutableArray *)mCloudFiles{

    if (_mCloudFiles == nil) {
        _mCloudFiles = [NSMutableArray array];
    }
    
    return _mCloudFiles;
}

//获取本地存放本地文件的目录
-(NSString *)getLocalFilePath:(BOOL)userFile{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = paths[0];
    NSString *localPath = [path stringByAppendingPathComponent:@"fileSync"];
    if (![FileUtil isFileExistWithFilePath:localPath]) {
        [FileUtil mkdirWithPath:localPath];
    }
    
    if (userFile) {
        
        localPath = [localPath stringByAppendingPathComponent:[[UserDefaultsUtil shareInstance]getString:LC_USERGUID]];
        [FileUtil mkdirWithPath:localPath];
    }
    
    return localPath;
}

- (BOOL)isFileExist:(NSString *)fileName{
    for (FileInfo *fileInfo in self.mfiles ) {
        if ([fileInfo.fileName isEqualToString:fileName]) {
            return YES;
        }
        
    }
    return NO;
    
}

- (void)loadCloudFileInfo{

    NSString *url = [ApiSupport getFileSyncUrl];
    if (url == nil) {
        return;
    }
    NSString *userGuid = [[UserDefaultsUtil shareInstance]getString:LC_USERGUID];
    //设置参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"userGUID"] = userGuid;
    if ([StringUtil isEmpty:userGuid]) {
        return;
    }
    NSDictionary *dict = [HttpUtil postWithUrl:url withDict:params withType:@"argv"];
    [self.mCloudFiles removeAllObjects];
    if ([dict[@"result"] isEqualToString:@"success"]) {
        NSArray *fileListArray = [FileInfo fileSyncWithArray:dict[@"fileList"]];
        NSString *servAddr = [[UserDefaultsUtil shareInstance]getString:LC_SERVADDR];
        if (servAddr != nil && [StringUtil isIp:servAddr]) {
            for (FileInfo *fileInfo in fileListArray) {
                NSString *downloadUrl = [NSString stringWithFormat:@"http://%@/%@",servAddr,fileInfo.filePath];
                NSString *fileName = [NSString stringWithFormat:@"%@&%@",fileInfo.fileTime,fileInfo.fileName];
                fileInfo.downloadUrl = downloadUrl;
                
                fileInfo.fileName = fileName;
                [fileInfo updateState];
                [self.mfiles addObject:fileInfo];
                [self.mCloudFiles addObject:[NSString stringWithFormat:@"%@%@",fileInfo.fileName,fileInfo.fileTime]];
            }
        }
    }
}
- (void)loadLocalFileInfo{
    
    NSArray *localFiles = [FileUtil getSortedChilds:[self getLocalFilePath:YES]];
    if (localFiles != nil) {
        for (NSString *fileName in localFiles) {
            FileInfo *fileInfo = [[FileInfo alloc]init];
            fileInfo.fileName = fileName;
            fileInfo.fileTime = [StringUtil getTimeSubString:fileName];
            fileInfo.localExist = YES;
            NSString *localPath = [NSString stringWithFormat:@"%@/%@",[self getLocalFilePath:YES],fileInfo.fileName];
            fileInfo.localPath = localPath;
            if (![self isFileExist:fileInfo.fileName]) {
                [self.mfiles addObject:fileInfo];
            }
        }
    }
    NSSortDescriptor *sortDes = [[NSSortDescriptor alloc] initWithKey:@"fileTime" ascending:NO]; // 降序
    [self.mfiles sortUsingDescriptors:@[sortDes]];
    
}

//判断本地文件是否存在
- (BOOL)isLocalFileExist:(NSString *)fileName{

    NSString *fileDir = [self getLocalFilePath:YES];
    
    NSString *filePath = [fileDir stringByAppendingPathComponent:fileName];
    
    return [FileUtil isFileExistWithFilePath:filePath];
}

- (void)loadCloudUndownloadFileCount{
    if (self.mFetching) {
        return;
    }
    
    self.mFetching = YES;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *url = [ApiSupport getFileSyncUrl];
        if ([StringUtil isEmpty:url]) {
            return;
        }
        NSString *userGuid = [[UserDefaultsUtil shareInstance]getString:LC_USERGUID];
        //设置参数
         NSMutableDictionary *params = [NSMutableDictionary dictionary];
          params[@"userGUID"] = userGuid;
        if ([StringUtil isEmpty:userGuid]) {
            return;
        }
        int count = 0;
        if (url != nil) {
            NSDictionary *dict = [HttpUtil postWithUrl:url withDict:params withType:@"argv"];
            if (dict == nil) {
                self.mFetching = NO;
                return ;
            }

            if ([dict[@"result"] isEqualToString:@"success"]) {
                NSArray *fileListArray = [FileInfo fileSyncWithArray:dict[@"fileList"]];
                for (FileInfo *fileInfo in fileListArray) {
                    NSString *fileName = [NSString stringWithFormat:@"%@&%@",fileInfo.fileTime,fileInfo.fileName];
                    fileInfo.fileName = fileName;
                    if (![self isLocalFileExist:fileName]) {
                        count++;
                        
                    }
                }
            }
            
            [[UserDefaultsUtil shareInstance]saveIntConfig:LC_UNREADEDFILE :count];
            
            self.mUnreadCountFetched = YES;
        }
        
        self.mFetching = NO;
    });
}

- (void)reloadFileInfo{

    [self.mfiles removeAllObjects];
    [self.mCloudFiles removeAllObjects];
    NetManager *netManager = [[NetManager alloc]init];
    if ([netManager isOpenNetwork]) {
        [self loadCloudFileInfo];
    }
    
    [self loadLocalFileInfo];
    int undownlaodedCount = 0;
    for (FileInfo *fileInfo in self.mfiles) {
        if (!fileInfo.localExist) {
            undownlaodedCount++;
        }
    }
    [[UserDefaultsUtil shareInstance]saveIntConfig:LC_UNREADEDFILE :undownlaodedCount ];
}

- (BOOL)isRemotedFileExist:(NSString *)fileName{
    

    if ([self.mCloudFiles indexOfObject:fileName] != NSNotFound) {
        return YES;
    }
    return NO;
}

- (NSArray<FileInfo *> *)getFileInfos{
    return self.mfiles;
    
}

- (NSInteger)getUndowloadedFileCount:(BOOL)forceFetch{
    if (!self.mUnreadCountFetched || forceFetch) {
        [self loadCloudUndownloadFileCount];
    }
    
    return [[UserDefaultsUtil shareInstance]getInt:LC_UNREADEDFILE];
}

//删除本地所有文件
- (void)deleteLocalFiles{
    //获取本地存放文件的目录路径
    NSString *dirPath = [self getLocalFilePath:YES];
    NSArray *fileList = [FileUtil getFileListFromDirectory:dirPath];
    [fileList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *filePath = [dirPath stringByAppendingPathComponent:obj];
        HRLog(@"文件里的路径dfhdfdf === %@",filePath);
        [FileUtil deleteFileWithfilePath:filePath];
    }];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"cloudReloadData" object:nil];
}

//删除指定文件(包括删除本地文件和控制台文件)
- (void)deleteLocalFile:(FileInfo *)fileInfo{
    [FileUtil deleteFileWithfilePath:fileInfo.localPath];
}
@end
